package com.example.demo.services.system.task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class Task {
    public String number;
    public List<String> param;
    public int now;
    public int max;

    public String result;

    public String taskId;

    public Task(String number) {
        this(number, new ArrayList<>());
    }

    public Task(String number, List<String> param) {
        this(number, param, 100);
    }

    public Task(String number, List<String> param, int max) {
        this(number, param, 0, max);
    }

    public Task(String number, List<String> param, int now, int max) {
        this.number = number;
        this.param = param;
        this.now = now;
        this.max = max;
    }

    public Task(String number, String... param) {
        this(number, 100, param);
    }

    public Task(String number, int max, String... param) {
        this(number, 0, max, param);
    }

    public Task(String number, int now, int max, String... param) {
        this(number, new ArrayList<>(Arrays.asList(param)), now, max);
    }

    public void step(int i) {
        now = now + i;
        //通知数据库再进一步
        TaskService.taskStep(taskId, String.valueOf(now));
    }

    public void step() {
        step(1);
    }

    public boolean preRun() {
        return true;
    }

    public abstract void run();

    public void afterRun() {

    }

    public boolean catchError(Throwable throwable) {
        //出错处理，模拟e.printStackTrace()
        StringBuffer buffer = new StringBuffer();
        buffer.append(throwable.getMessage());
        buffer.append("\n");
        buffer.append(throwable);
        buffer.append("\n");
        StackTraceElement[] trace = throwable.getStackTrace();
        for (StackTraceElement traceElement : trace) {
            buffer.append("\tat " + traceElement);
            buffer.append("\n");
        }
        result = buffer.toString();
        return false;
    }
}
